#!/bin/sh
# Grabs a snapshot for timelapse by cron

. /usr/share/common

TIMELAPSE_CONFIG_FILE="/etc/timelapse.json"

tl_enabled=$(jct $TIMELAPSE_CONFIG_FILE get enabled)
tl_mount=$(jct $TIMELAPSE_CONFIG_FILE get mount)
tl_filepath=$(jct $TIMELAPSE_CONFIG_FILE get filepath)
tl_filename=$(jct $TIMELAPSE_CONFIG_FILE get filename)
tl_interval=$(jct $TIMELAPSE_CONFIG_FILE get interval)
tl_keep_days=$(jct $TIMELAPSE_CONFIG_FILE get keep_days)

hesitate() {
	echo_warning "$1"
	sleep 5
	exit 0
}

# drop trailing slashes
tl_mount=${tl_mount%/}
tl_filepath=${tl_filepath%/}

if [ -z "$tl_mount" ]; then
	echo_error "'tl_mount' is not set"
	exit 1
fi

# wait for mount point
if ! mountpoint -q "$tl_mount" >/dev/null; then
	hesitate "$tl_mount is not mounted"
fi

if [ ! -w "$tl_mount" ]; then
	hesitate "$tl_mount is not writable"
fi

# storage directory
tl_storage="$tl_mount/$tl_filepath"
ensure_dir "$tl_storage"

if [ -z "$tl_keep_days" ]; then
	tl_keep_days=7
fi

if [ -z "$tl_filename" ]; then
	tl_filename="%Y/%m/%d/%H%M.jpg"
fi

if [ -z "$tl_interval" ]; then
	tl_interval=1
fi

# delete older files
find "$tl_storage" -type f -name '*.jpg' -mtime +$tl_keep_days -delete

# delete empty directories
find "$tl_storage" -mindepth 1 -type d -empty -delete

target="$tl_storage/$(date +"$tl_filename")"
ensure_dir "$(dirname "$target")"
prudyntctl snapshot -c 0 > "$target"

exit 0
